import sys
sys.path.append("..")
from Core.include import *
from Core import Tav
from Base import TaskModel, Singleton


class GernelInfo():
    def __init__(self):
        self.file_name = ""
        self.file_type = ""
        self.tav_virusname = ""
        

class GernelExtractResult():
    def __init__(self, bSuccess, gernel_info):
        self.bSuccess = bSuccess
        self.gernel_info = gernel_info



class GernelExecutor(TaskModel.Executor):
    def __init__(self):
        self.tav = Tav.Tav.Instance()
        self.tav.Start()
        
    def Exec(self, task):
        filename = task.filename
        bSuccess, gernel_info = self.Extract(filename)
        return GernelExtractResult(bSuccess, gernel_info)

    def Extract(self, filename):
        tav_scan_result = self.tav.Scan__(filename)
        gernel_info = GernelInfo()
        gernel_info.file_name = filename
        gernel_info.file_type = tav_scan_result.tav_result.file_type
        gernel_info.tav_virusname = tav_scan_result.tav_result.virus_name
        return (True, gernel_info)
        


class GernelExtractTask(TaskModel.Task):
    def __init__(self, filename):
        TaskModel.Task.__init__(self)
        self.filename = filename
        
    
class GernelTaskProcessor(TaskModel.TaskModel):
    def __init__(self):
        TaskModel.TaskModel.__init__(self)
        
    def CreateExecutor(self):
        return GernelExecutor()
    
    def Notify(self, observer, task, result):
        observer.OnGernelInfoExtractComplete(result.bSuccess, result.gernel_info)

    def Extract(self, filename):
        self.PostTask(GernelExtractTask(filename))

    def Extracts(self, filename_list):
        for filename in filename_list:
            self.Extract(filename)
      

    

class GernelPlugin(Singleton.Singleton):
    def __init__(self):
        self.processor = GernelTaskProcessor()
        self.processor.AddObserver(self)
        self.processor.Start()
        self.data_map = {}

        
    def GetData(self):
        return self.data_map

    def OnPluginNotify(self, param):
        if (param.event == FILE_DOWNLOAD_COMPLETE):
            self.processor.Extract(param.filename)
        if param.event == FILE_REMOVE:
            del self.data_map[param.filename]
            

    def OnGernelInfoExtractComplete(self, bSuccess, genrnel_info):
        if (bSuccess):
            self.data_map[genrnel_info.file_name] = genrnel_info
        else:
            print "GernelInfo Extract Fail."
            


    
if __name__ == '__main__':
    param = PluginNotifyParam(FILE_DOWNLOAD_COMPLETE, "V:\\Download\\C53DC46FBAD0C3551CFD27C10D776554")
    plugin = GernelPlugin()
    plugin.OnPluginNotify(param)

            
            